﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PegasCompany.Data;
using PegasCompany.Helper;
using PegasCompany.Tools;
using PegasCompany.Tools.Storage;
using PegasCompany.Tools.Text;

namespace PegasCompany.AdminPanel
{
    public partial class Default : Page
    {
        private Int32 CurrentYear
        {
            get
            {
                return ViewState["CurrentYear"] != null ? Convert.ToInt32(ViewState["CurrentYear"]) : -1;
            }
            set
            {
                ViewState["CurrentYear"] = value;
            }
        }
        private SiteContent CurrentSiteContent
        {
            get { return (SiteContent)ViewState["CurrentSiteContent"]; }
            set { ViewState["CurrentSiteContent"] = value; }
        }

        private Int32 SiteContentType
        {
            get
            {
                return ViewState["SiteContentType"] != null
                    ? Convert.ToInt32(ViewState["SiteContentType"])
                    : -1;
            }
            set
            {
                ViewState["SiteContentType"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!Request.QueryString.HasKeys())
                {
                    mvContentEditor.ActiveViewIndex = 0;
                }
                else
                {
                    string sContentType = Request.QueryString["edit"];
                    if (!string.IsNullOrEmpty(sContentType))
                    {
                        if (Enum.GetNames(typeof(EnumHelper.ContentType)).Contains(sContentType))
                        {
                            SessionHelper.Url = "/AdminPanel/";
                            LoadEditorForContent((int)Enum.Parse(typeof(EnumHelper.ContentType), sContentType));
                        }
                        else if (Enum.GetNames(typeof(EnumHelper.ListContentType)).Contains(sContentType))
                        {
                            CurrentYear = FillYears();
                            if (!String.IsNullOrEmpty(Request.QueryString["year"]))
                            {
                                string sYear = Request.QueryString["year"];
                                int iYear;

                                if (int.TryParse(sYear, out iYear))
                                {
                                    CurrentYear = iYear;
                                    LoadList((int)Enum.Parse(typeof(EnumHelper.ListContentType), sContentType), CurrentYear);
                                }
                            }
                            else
                            {
                                SessionHelper.Url = Request.Url.OriginalString;
                                LoadList((int)Enum.Parse(typeof(EnumHelper.ListContentType), sContentType), CurrentYear);
                            }
                        }
                        else
                        {
                            Response.Redirect("/AdminPanel/");
                        }
                    }
                }
            }
        }

        private int FillYears()
        {
            IOrderedEnumerable<int> lYearList = SiteContent.ListAllContentYear((int)EnumHelper.ListContentType.News).OrderByDescending(i => i);
            //rptSubMenu.DataSource = lYearList;
            //rptSubMenu.DataBind();

            return lYearList.First();
        }
        private void LoadList(int iTargetListContentType, int iYear)
        {
            mvContentEditor.ActiveViewIndex = 2;

            SiteContentType = iTargetListContentType;

            List<SiteContent> scList = SiteContent.ListAllContent(iTargetListContentType, iYear);
            rptList.DataSource = scList;
            rptList.DataBind();
        }

        private void LoadEditorForNewListItem(int iTargetContentType)
        {
            mvContentEditor.ActiveViewIndex = 1;
            SiteContentType = iTargetContentType;
        }

        private void LoadEditorForEditListItem(int iContentId)
        {
            mvContentEditor.ActiveViewIndex = 1;

            SiteContent sc = SiteContent.Get(iContentId);
            if (sc != null && sc.ContentTypeCode.HasValue && sc.SiteContentId.HasValue)
            {
                CurrentSiteContent = sc;

                SiteContentType = sc.ContentTypeCode.Value;
                FillFileAttachList(sc.SiteContentId.Value);

                txtTitle.Text = sc.Title;
                txtDescription.Text = sc.Description;
                ckContent.Text = sc.Content;
            }
        }

        private void SaveAttach(int iSiteContentId)
        {
            if (String.IsNullOrEmpty(fuAttachFile.FileName))
                return;

            if (!fuAttachFile.HasFile || !FileValidate(fuAttachFile.PostedFile.ContentType))
                return;

            string sFullPath = Path.Combine(Server.MapPath(ConfigReader.SiteContentAttachmentPath), fuAttachFile.FileName);

            FileStream fsWriteAttachmentStream = new FileStream(sFullPath, FileMode.Create, FileAccess.ReadWrite);
            using (BinaryWriter binWriter = new BinaryWriter(fsWriteAttachmentStream))
            {
                binWriter.Write(FileHelper.ReadFileContent(fuAttachFile.PostedFile.InputStream));
                binWriter.Close();
            }

            if (!File.Exists(sFullPath))
                return;

            FileAttach emailTemplateAttach = new FileAttach
            {
                SiteContentId = iSiteContentId,
                DocumentName = fuAttachFile.FileName,
                DocumentType = fuAttachFile.PostedFile.ContentType,
                DocumentSize = fuAttachFile.PostedFile.ContentLength
            };

            emailTemplateAttach.Save();
            if (!emailTemplateAttach.AttachId.HasValue)
                return;

            FillFileAttachList(iSiteContentId);
        }

        private void FillFileAttachList(int siteContentId)
        {
            btnSaveAttach.Visible = true;

            List<FileAttach> listFileAttach = FileAttach.ListBySiteContentId(siteContentId);
            if (listFileAttach != null)
            {
                rptContentAttach.DataSource = listFileAttach;
                rptContentAttach.DataBind();
            }
        }


        protected bool FileValidate(string sContentType)
        {
            string[] sGrantedTypes = TextHelper.AllowedFileTypes;
            return Array.IndexOf(sGrantedTypes, sContentType) != -1;
        }

        private void LoadEditorForContent(int iTargetContentType)
        {
            mvContentEditor.ActiveViewIndex = 1;

            SiteContentType = iTargetContentType;

            SiteContent targetSiteContent = new SiteContent();

            List<SiteContent> sc = SiteContent.ListAllContent(iTargetContentType);
            if (sc != null && sc.Count > 0)
            {
                targetSiteContent = sc.SingleOrDefault();
            }
            else
            {
                targetSiteContent.SaveEmpty(iTargetContentType);
            }

            if (targetSiteContent != null && targetSiteContent.SiteContentId != null)
            {
                CurrentSiteContent = targetSiteContent;
                FillFileAttachList(targetSiteContent.SiteContentId.Value);

                txtTitle.Text = targetSiteContent.Title;
                txtDescription.Text = targetSiteContent.Description;
                ckContent.Text = targetSiteContent.Content;
            }
        }

        protected void BtnSaveClick(object sender, EventArgs eventArgs)
        {
            if (CurrentSiteContent != null)
            {
                CurrentSiteContent.Title = txtTitle.Text.Trim();
                CurrentSiteContent.Description = txtDescription.Text.Trim();
                CurrentSiteContent.Content = ckContent.Text;
                CurrentSiteContent.UpdateInstance();
            }
            else
            {
                SiteContent sc = new SiteContent
                {
                    ContentTypeCode = SiteContentType,
                    Content = ckContent.Text,
                    Title = txtTitle.Text.Trim(),
                    Description = txtDescription.Text.Trim()
                };

                sc.Save();
            }
            Response.Redirect(SessionHelper.Url);
        }

        protected void btnAddListItem_Click(object sender, EventArgs e)
        {
            LoadEditorForNewListItem(SiteContentType);
        }

        protected void rptList_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            int iListItemId;
            if (int.TryParse(e.CommandArgument.ToString(), out iListItemId))
            {
                if (e.CommandName.Equals("DeleteListItem", StringComparison.OrdinalIgnoreCase))
                {
                    SiteContent.Get(iListItemId).MarkAsDeleted();
                    if (SiteContentType != -1)
                    {
                        LoadList(SiteContentType, CurrentYear);
                    }
                }
                else if (e.CommandName.Equals("EditListItem", StringComparison.OrdinalIgnoreCase))
                {
                    LoadEditorForEditListItem(iListItemId);
                }
            }
        }

        protected void btnSaveAttach_Click(object sender, EventArgs e)
        {
            if (CurrentSiteContent != null && CurrentSiteContent.SiteContentId.HasValue)
            {
                SaveAttach(CurrentSiteContent.SiteContentId.Value);
            }
        }

        protected void rptContentAttach_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DeleteAttach")
            {
                int iAttachId = Convert.ToInt32(e.CommandArgument);
                FileAttach fileAttach = FileAttach.Get(iAttachId);
                fileAttach.IsDeleted = true;

                fileAttach.UpdateInstance();

                if (CurrentSiteContent.SiteContentId != null)
                {
                    FillFileAttachList(CurrentSiteContent.SiteContentId.Value);
                }
            }
            else if (e.CommandName == "OpenAttach")
            {
                int iAttachId = Convert.ToInt32(e.CommandArgument);
                FileAttach fileAttach = FileAttach.Get(iAttachId);
                if (fileAttach != null)
                {
                    Response.Redirect(Path.Combine(ConfigReader.SiteContentAttachmentPath, fileAttach.DocumentName));
                }
            }
        }
    }
}